
import wx
import os
import sys
from sqloper import *
from pathutil import *
from setup import ConfigWindow
from MoveOper import LogWin
import ConfigParser
import string
import logging
import shutil



logging.basicConfig(level=logging.DEBUG, filename='xbfm.log',
                    format='%(asctime)s %(levelname)s: %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

clogger = logging.getLogger("console_Log")

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
ch.args=(sys.stdout,format)

clogger.addHandler(ch)
logging.debug('xbfm started')
#clogger.debug('xbfm started')
Config = ConfigParser.ConfigParser()
Config.read("config.ini")
DSF = Config.get('SETTINGS','DSF')
SSF = Config.get('SETTINGS','SSF')
XBMCDIR = Config.get('SETTINGS','XBMCDIR')
FANARTPATH = Config.get('SETTINGS','FANARTPATH')
THUMBSPATH = Config.get('SETTINGS','THUMBSPATH')
#SQLDIR = Config.get('SETTINGS','SQLDIR')
#DBUSER = Config.get('SETTINGS','DBUSER')
#DBPASS = Config.get('SETTINGS','DBPASS')
DBTYPE = Config.get('SETTINGS','DBTYPE')

ostype    = os.name
platform = sys.platform
SSrc='.'
DSrc='.'
if os.path.isdir(SSF):
    SSrc = SSF
if os.path.isdir(DSF):
    DSrc = DSF

CbxCPF = False
Total_Items = 0

ID_ABOUT = 101
ID_EXIT  = 102
ID_UTIL  = 103
ID_EDIT  = 104
ID_HELP  = 105
ID_CONFIG = 106




def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3,
 wxID_FRAME1DIRCTRL1, wxID_FRAME1DIRCTRL2, wxID_FRAME1MOVELIST,
 wxID_FRAME1PANEL1, wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2,
 wxID_FRAME1STATICTEXT3, wxID_FRAME1BUTTON4,wxID_FRAME1CHECKBOX1,
 wxID_FRAME1TXT1,] = [wx.NewId() for _init_ctrls in range(14)]



class Frame1(wx.Frame):

    def _init_ctrls(self, prnt):

        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(100, 200), size=wx.Size(950,600),
              style=wx.DEFAULT_FRAME_STYLE, title='XBFM File Mover')


        self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(1920, 1080),
              style=wx.TAB_TRAVERSAL)

        self.index = 0


        self.DirCtrl1 = wx.GenericDirCtrl(defaultFilter=0, dir=SSrc,
              filter='', id=wxID_FRAME1DIRCTRL1, name='DirCtrl1',
              parent=self.panel1, pos=wx.Point(-1, -1), size=wx.Size(-1,-1),
              style=wx.DIRCTRL_3D_INTERNAL | wx.SUNKEN_BORDER)
        self.DirCtrl1.ShowHidden(True)
        self.SelSource = self.DirCtrl1.GetTreeCtrl()
        #self.SelSource.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnSourceRightClick)

        self.DirCtrl2 = wx.GenericDirCtrl(defaultFilter=0, dir=DSrc,
              filter='', id=wxID_FRAME1DIRCTRL2, name='DirCtrl2',
              parent=self.panel1, pos=wx.Point(-1, -1), size=wx.Size(-1, -1),
              style=wx.DIRCTRL_3D_INTERNAL | wx.SUNKEN_BORDER)
        self.SelDest = self.DirCtrl2.GetTreeCtrl()
        self.DirCtrl2.ShowHidden(True)
        #self.SelDest.Bind(wx.EVT_TREE_RIGHT_DOWN, self.OnDestRightClick, self.SelDest)
        self.SelDest.Bind(wx.EVT_RIGHT_UP, self.OnDestRightUp)

        self.MoveList = wx.ListCtrl( id=wxID_FRAME1MOVELIST,
              parent=self.panel1, pos=wx.Point(-1, -1),
              size=wx.Size(-1, -1), style=wx.LC_REPORT)
        self.MoveList.InsertColumn(0, 'Source', width=400)
        self.MoveList.InsertColumn(1, 'Destination', width=300)
        self.MoveList.InsertColumn(2, 'CreateParent', width=4)

        self.MoveList.Bind(wx.EVT_RIGHT_UP, self.OnMovelistRightUp)
        self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label=u'Quit',
              name='button1', parent=self.panel1, pos=wx.Point(-1, -1),
              size=wx.Size(-1, -1), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
              id=wxID_FRAME1BUTTON1)
        self.panel1.Bind(wx.EVT_ENTER_WINDOW, self.OnListBox1Listbox, id = 1)

        self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label=u'Move Now',
              name='button2', parent=self.panel1, pos=wx.Point(-1, -1),
              size=wx.Size(-1, -1), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
              id=wxID_FRAME1BUTTON2)
        self.checkbox1 = wx.CheckBox(id=wxID_FRAME1CHECKBOX1, parent=self.panel1,
              pos=wx.Point(-1,-1),label='Create Parent Folders', name = 'checkbox1')
        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label=u'Source Dir', name='staticText1', parent=self.panel1,
              pos=wx.Point(-1, -1), size=wx.Size(-1, -1), style=0)

        self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
              label=u'Destination Dir', name='staticText2', parent=self.panel1,
              pos=wx.Point(-1, -1), size=wx.Size(-1, -1), style=0)

        self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,
              label=u'  Items in Queue: %s' % Total_Items, name='staticText3', parent=self.panel1,
              pos=wx.Point(-1, -1), size=wx.Size(-1, -1), style=0)

        self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Remove',
              name='button3', parent=self.panel1, pos=wx.Point(-1, -1),
              size=wx.Size(-1, -1), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button,
              id=wxID_FRAME1BUTTON3)
        buttonlabel = u"Add to\n".center(5) + "Queue".center(5)
        self.button4 = wx.Button(id=wxID_FRAME1BUTTON4, label=buttonlabel,
              name='button4', parent=self.panel1, pos=wx.Point(860, 160),
              size=wx.Size(-1,-1), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnButton4Button,
              id=wxID_FRAME1BUTTON4)
       
        topSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.panel1.SetSizer(topSizer)
        vgap = hgap = 10
        gbagsizer = wx.GridBagSizer(vgap, hgap)

        b = 0
        gbagsizer.Add(self.staticText1, (0,0 ), (1,1), wx.EXPAND | wx.ALL, b)

        gbagsizer.Add(self.DirCtrl1,(1,0 ), (2,1), wx.EXPAND | wx.ALL, b)
        gbagsizer.Add(self.staticText2,(0,1 ),(1,1), wx.EXPAND | wx.ALL, b)
        gbagsizer.Add(self.DirCtrl2,(1, 1), (2,2), wx.EXPAND | wx.ALL, b)
        gbagsizer.Add(self.MoveList,(3, 0), (2, 4), wx.EXPAND | wx.ALL, b)
        gbagsizer.Add(self.button1, (0, 5), (1, 1), wx.RIGHT | wx.ALL, b)
        gbagsizer.Add(self.button2, (3, 5), (1, 1), wx.RIGHT |wx.TOP| wx.ALL, b)
        gbagsizer.Add(self.button3, (4, 5), (1, 1), wx.RIGHT |wx.BOTTOM |wx.ALL, b)
        gbagsizer.Add(self.button4, (2, 5), (1, 1), wx.RIGHT |wx.BOTTOM |wx.ALL, b)
        gbagsizer.Add(self.staticText3,(5,0 ),(1,1), wx.CENTER | wx.ALL,b)
        gbagsizer.Add(self.checkbox1,(5, 1), (1,1), wx.CENTER | wx.ALL,b)

        #gbagsizer.AddGrowableRow(0)
        gbagsizer.AddGrowableRow(1)
        gbagsizer.AddGrowableRow(2)
        gbagsizer.AddGrowableRow(3)
        gbagsizer.AddGrowableRow(4)

        gbagsizer.AddGrowableCol(0)
        gbagsizer.AddGrowableCol(1)
        gbagsizer.AddGrowableCol(2)
        gbagsizer.AddGrowableCol(3)
        gbagsizer.AddGrowableCol(4)
        gbagsizer.AddGrowableCol(5)



        self.SetSizer(gbagsizer)

        menuBar = wx.MenuBar()

        menu1 = wx.Menu()
        menuBar.Append(menu1, "&File.....")
        menuItem1 = menu1.Append(-1, "&Exit...")

        menu2 = wx.Menu()
        menuBar.Append(menu2, "&Edit.....")
        menuItem2 = menu2.Append(-1, "&Edit MyVideos")
        menuItem6 = menu2.Append(-1, "&Edit Settings")

        menu3 = wx.Menu()
        menuBar.Append(menu3, "&Utils.....")
        menuItem3 = menu3.Append(-1, "&Movies to Folders")
        menuItem4 = menu3.Append(-1, "&TV Shows to Season Folders")
        menuItem5 = menu3.Append(-1, "&TBD - Open to suggestions")

        self.SetMenuBar(menuBar)
        self.Bind(wx.EVT_MENU, self.OnButton1Button, menuItem1)
        self.Bind(wx.EVT_MENU, self.Edit_Config, menuItem6)
        self.Bind(wx.EVT_MENU, self.Movies2Folders, menuItem3)
        self.Bind(wx.EVT_MENU, self.TV2Seasons, menuItem4)
        self.Bind(wx.EVT_MENU, self.DelUnusedThumbs, menuItem5)

    def __init__(self, parent):
        self._init_ctrls(parent)
       # self.LogWin.SetBackgroundColour(wx.Colour(0, 0, 0))
       # self.LogWin.SetForegroundColour(wx.Colour(255, 255, 255))
        #self.LogWin.Show(False)
        self.checkbox1.SetValue(CbxCPF)
        if THUMBSPATH =='' or FANARTPATH =='' or XBMCDIR =='':
            win = ConfigWindow(self)
            win.ShowModal()
            wx.MessageBox("XBFM needs to be restarted")
                     
            self.Close()

#Returns Mount Point
    def getMount(path):
        oldpath = path
        path = os.path.abspath(path)
        while path != os.path.sep:
            if os.path.ismount(path):
                newpath =  path
                #print newpath
            path = os.path.abspath(os.path.join(path, os.pardir))
            #newpath = oldpath.replace(path,"",1)
        return newpath




    def isnumber(strx):
        try:
            int(strx)
            return True
        except ValueError:
            return False

    def Edit_Config(self,event):
        win = ConfigWindow(self)
        win.ShowModal()

    def Movies2Folders(self,event):
        self.staticText1.SetLabel("Movies2Folders Src")
        self.staticText2.SetLabel("Movies2Folders Dest")        
        #wx.MessageBox("This will move selected movie files into folders named the same as the Movie Title then make the necessary database changes. You can select an entire folder or individual movies.")
        dlg = wx.MessageDialog(None, "When implemented this will move selected movie files into folders named the same as the Movie Title then make the necessary database changes. You can select an entire folder or individual movies. Proceed?",'Choose!',wx.YES_NO | wx.ICON_QUESTION)
        retCode = dlg.ShowModal()
        if (retCode == wx.ID_NO):
            self.staticText1.SetLabel("Source Dir")
            self.staticText2.SetLabel("Destination Dir")
        if (retCode == wx.ID_YES):
            return
        #seudo code
         # ShowSelectionBox
         # select master destination folder 
         # select folder or set of movies
         # for each item in Movies2Folders
         # strFileName = item[0]
         # lookup movie title associated with filename
         # getMovieTitle(strFileName)
         # os.mkdir(MovieTitle)
         # AddToQueue(Source,Destination)
         # Press MoveNow button
        
         
        return    
    def TV2Seasons(self,event):    
        self.staticText1.SetLabel("TV2Epiesodes Src")
        self.staticText2.SetLabel("TV2Episodes Dest")   
       
        dlg = wx.MessageDialog(None, "When implemented this will move selected TV episodes into season folders then make the necessary database changes. Select one show at a time and add to queue. Destination window is only used if you wish to move to alternate location and the Alternate Location box is checked. Proceed?",'Choose!',wx.YES_NO | wx.ICON_QUESTION)
        retCode = dlg.ShowModal()
        if (retCode == wx.ID_NO):
            self.staticText1.SetLabel("Source Dir")
            self.staticText2.SetLabel("Destination Dir")
            
        if (retCode == wx.ID_YES):
            return   
   
    def DelUnusedThumbs(self,event):
        wx.MessageBox("This will make a list of every thumbnail associated with your video library and delete those that appear to be orphans")
    def OnDestRightUp(self,event):
        DirPath = self.DirCtrl2.GetPath()
        dialog = wx.TextEntryDialog(None, "Create New Folder?","Create Folder", "%s"%DirPath + " ", style=wx.OK|wx.CANCEL)
        if dialog.ShowModal() == wx.ID_OK:
            os.mkdir(dialog.GetValue())
            self.DirCtrl2.ReCreateTree()
        
    def OnListBox1Listbox(self, event):
        self.MoveList.Bind(wx.EVT_LISTBOX_RIGHT_UP,self.OnDestRightClilck)
        self.MoveList.Bind(wx.EVT_ENTER_WINDOW,self.OnEnterMoveList)
        #event.Skip()
    def OnEnterMoveList(self, event):
        self.MoveList.SetStatusText('Select item and Rclick to see record')

    def OnButton3Button(self,event):

        #Remove Highlighted item from Move Queue
        Move_Index = self.MoveList.GetFirstSelected()
        if Move_Index == -1:
            event.Skip()
        #print str(Move_Index)
        self.MoveList.DeleteItem(Move_Index)
        Move_Index == -1
        Total_Items = self.MoveList.GetItemCount()
        self.staticText3.SetLabel(u'Items in Queue: %s' % Total_Items)
        logging.debug(u"Move Record Removed from Queue")
    def OnTreeCtrl1TreeSelChanged(self, event):
        event.Skip()
 # returns free drive space - Only for Unix systems
    def freespace(p):
        s = os.statvfs(p)
    # return s.f_bsize * s.f_bavail

    def OnMovelistRightUp(self, event):
        Tot = self.MoveList.GetItemCount()
        if Tot > 0:
            i = self.MoveList.GetFirstSelected()
            SourceDir = self.MoveList.GetItem(i,0).GetText()
            DestDir = self.MoveList.GetItem(i,1).GetText()
            Destfldr = os.path.basename(SourceDir)
            DestDir = DestDir+os.sep+Destfldr
            CPF = self.MoveList.GetItem(i,2).GetText()
            wx.MessageBox("\n\n Move From:%s  \n\n"%SourceDir +" Move To: %s  " %DestDir + "   Create Parent = %s" %CPF)
#Move items in Queue - 3-18-2011 Moved code to MoveOper.py which redirects
#stdout to transaction window.
    def OnButton2Button(self, event):
        Total_Items = self.MoveList.GetItemCount()
        # only run if there's records in move queue
        if Total_Items == 0:
            wx.MessageBox("No Items to Move!")
            event.Skip()
        if Total_Items != 0:
            #Send Queue List to move module
            win = LogWin(self.MoveList)
            win.ShowModal()
            win.Destroy()
            self.DirCtrl2.ReCreateTree()
            self.DirCtrl1.ReCreateTree()
            self.checkbox1.SetValue(False)
            Total_Items = self.MoveList.GetItemCount()
            self.staticText3.SetLabel(u'Items in Queue: %s' % Total_Items)
    
    def OnDestRightClick(self, event):
        #print ("Destination \"%s" % self.DirCtrl2.GetPath())
        event.Skip()

    def OnDestSelect(self, event):
        event.Skip()
# Add items to move queue - Nothing is moved or written to database yet
    def OnButton4Button(self, event):
        
        SourceDir =  self.DirCtrl1.GetPath()
        DestDir   =  self.DirCtrl2.GetPath()
        self.index = self.MoveList.GetItemCount()
        if os.path.isdir(SourceDir) and getDirectorySize(SourceDir)==0:
            wx.MessageBox(u"Source Folder is Empty!")
            return
        if os.path.isdir(DestDir):
            srcBase,srcTail = os.path.split(SourceDir)
            destBase,destTail = os.path.split(DestDir)
            TempDir = DestDir + os.sep + srcTail
            if os.path.isdir(TempDir):
                wx.MessageBox(u"Destination Folder Already Exists!    Try adding subfolders.")
                return
        if os.path.isfile(DestDir):
            wx.MessageBox(u"Destination must be a Folder!")
            return
        # Treelist = self.DirCtrl1().TreeCtrl().get_children
        t = self.MoveList.GetItemCount()
        while t > 0:
            t = t -1
            tempdir = self.MoveList.GetItem(t,0).GetText()
            if tempdir == SourceDir:
                wx.MessageBox(u"Folder is already in Queue")
                return


        # Create Parent Folder Flag - if checked join folders to
        # duplicate source path. Default is checked
        CPF = "OFF"
        if self.checkbox1.GetValue() == False:
            if DestDir == getMount(DestDir):

                dlg = wx.MessageDialog(None, u"Destination is Root Drive - CPF flag is OFF! - Continue Y/N?",'Choose!',wx.YES_NO | wx.ICON_QUESTION)
                retCode = dlg.ShowModal()
                if (retCode == wx.ID_NO):
                    return


        if self.checkbox1.GetValue():
            # Get folder name minus mount point /media/Drivename/FolderName or C:\Foldername
            # returns /FolderName
            RootFolder = getRootFolder(SourceDir)
            #Find root drive or Mount Point of Destination
            PathDir = getMount(DestDir)
            srcRoot = getMount(SourceDir)
            if PathDir == srcRoot:
                wx.MessageBox("Can not use CPF Flag when destination is on same drive")
                return
            #print "NewMount Folder %s" %PathDir
            NewDest = PathDir + RootFolder
            DestDir = NewDest
            CPF = "ON"
            #print "DestDir %s" %DestDir
        # Initial audits complete - Add to movelist

        line = "Line %s" % self.index
        self.MoveList.InsertStringItem(self.index, line)
        self.MoveList.SetStringItem(self.index, 0, SourceDir)
        self.MoveList.SetStringItem(self.index, 1, DestDir)
        self.MoveList.SetStringItem(self.index, 2, CPF)
        self.index += 1
        Total_Items = self.MoveList.GetItemCount()
        self.staticText3.SetLabel(u'Items in Queue: %s' % Total_Items)
        logging.debug(u"Adding to Move Queue - Create Parent Folder: %s" %CPF)
        logging.debug(u"Move Rec Source: %s" % SourceDir)
        logging.debug(u"Move Rec Dest: %s" % DestDir)

    # Exit button
    def OnButton1Button(self, event):
        self.Close()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = create(None)
    frame.Show()

    app.MainLoop()
